package com.mediacloud.app.newsmodule.fragment.video.live;

import static com.mediacloud.app.assembly.util.FunKt.toastCenter;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.mediacloud.app.assembly.util.DateParse;
import com.mediacloud.app.assembly.util.Utility;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.video.live.LiveProgramAdaptor;
import com.mediacloud.app.newsmodule.adaptor.video.live.LiveProgramAdaptor1;
import com.mediacloud.app.newsmodule.broadcast.LiveReplayBroadcast;
import com.mediacloud.app.newsmodule.broadcast.LiveReplayBroadcast.UpdateListState;
import com.mediacloud.app.newsmodule.fragment.recommend.ComponentLiveListFragment;
import com.mediacloud.app.newsmodule.model.SimpleNavigateItem;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.news.ProgramListItem;
import com.mediacloud.app.model.news.ProgramListItem.GuideItemState;
import com.mediacloud.app.newsmodule.utils.AppointmentController;
import com.mediacloud.app.reslib.enums.XKey;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.user.model.UserInfo;
import com.tencent.mmkv.MMKV;

import org.json.JSONObject;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 具体某个节目单
 *
 * @author x
 */
public class LiveProgramItemFragment extends BaseFragment implements UpdateListState {

    /**
     * 节目单table索引
     */
    public int liveTableIndex = 0;
    public ListView programList;
    protected View noProgram, isLoadingProgramList;
    protected SimpleNavigateItem catalogItem;
    protected Handler handler = new ProgramListHandle();
    public LiveProgramAdaptor liveProgramAdaptor;
    protected LiveReplayBroadcast liveReplayBroadcast;
    private String contentId;
    private String channelName;
    private View progressBar;
    private boolean isClick = false;

    AppointmentController appointmentController;
    ProgramListItem  currentItem;

    @Override
    public int getLayoutResID() {
        return R.layout.aappfactory_liveprogram_listitem;
    }

    @Override
    public void initView() {
        catalogItem = getFragmentArguments().getParcelable("data");
        programList = Utility.findViewById(mRootView, R.id.programList);
        progressBar = Utility.findViewById(mRootView, R.id.progressBar);
        //		programList.setPullLoadEnable(false);
        //		programList.setPullRefreshEnable(false);
        noProgram = Utility.findViewById(mRootView, R.id.noProgram);
        isLoadingProgramList = Utility.findViewById(mRootView, R.id.isLoadingProgramList);
        noProgram.setVisibility(View.GONE);
        isLoadingProgramList.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        handler.removeMessages(1);
        getActivity().unregisterReceiver(liveReplayBroadcast);
        liveReplayBroadcast.updateListState = null;
    }

    public static boolean isInPlay(long s, long e, long t) {
        return t > s && t < e;
    }


    @Override
    protected void initOther() {
        super.initOther();
        appointmentController = new AppointmentController(requireContext(), new AppointmentController.AppointmentStatusListener() {
            @Override
            public void onAppointmentStatus(String contentId, boolean appointmented) {

            }

            @Override
            public void onAppointmentOk(String contentId, boolean appointmented, long appointmentCount) {
                isClick = false;
                currentItem.setAppointment(appointmented);
                liveProgramAdaptor.notifyDataSetChanged();
            }

            @Override
            public void onAppointmentErr(String msg) {
                isClick = false;
            }
        });
        liveProgramAdaptor = new LiveProgramAdaptor1(getActivity(), false);
        programList.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                position = position - programList.getHeaderViewsCount();
                ProgramListItem item = liveProgramAdaptor.getItem(position);
                //如果选择的是空 或者  选中了当前的
                if (item == null || liveProgramAdaptor.selectedIndex == position) {
                    return;
                }
                GuideItemState itemState = ProgramListItem.getItemState(item);
                if (itemState == ProgramListItem.GuideItemState.REPLAY || itemState == ProgramListItem.GuideItemState.LIVE) {
                    if(itemState == ProgramListItem.GuideItemState.REPLAY){
                        Fragment f = getParentFragment();
                        if(f!=null && f instanceof ComponentLiveListFragment){
                            ((ComponentLiveListFragment) f).isFirstPlay = false;
                        }
                    }
                    liveProgramAdaptor.selectedIndex = position;
                    Intent intent = new Intent();
                    intent.setAction(LiveReplayBroadcast.PlayAction);
                    intent.putExtra("data", item);
                    LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);//发送广播  通知回看或是从回看切到直播
                    sendUpdateChoose();
                    liveProgramAdaptor.notifyDataSetChanged();
                } else if (itemState == ProgramListItem.GuideItemState.APPOINTMENTED||itemState == GuideItemState.COMING_SOON) {//预约/反预约
//                    if (!UserInfo.isLogin(getActivity())) {
//                        LoginUtils.invokeLogin(getActivity(), new Intent(), LoginUtils.INVOKE_LOGIN);
//                        return;
//                    }
                    if (isClick) return;
                    currentItem = item;
                  //  cancelAppointment(item);
                    isClick = true;
                    appointmentController.Appointment(contentId,channelName,3,item.getStarttime(), item.getEndtime(),item.getId()+"");
                } //else if (itemState == GuideItemState.COMING_SOON) {
//                    if (!UserInfo.isLogin(getActivity())) {
//                        LoginUtils.invokeLogin(getActivity(), new Intent(), LoginUtils.INVOKE_LOGIN);
//                        return;
//                    }
//                    long startTime = DateParse.parseDate(item.getStarttime(), null).getTime();
//                    long nowTime = new Date(System.currentTimeMillis()).getTime();
//                    int pushAppointmentTime =
//                            AppFactoryGlobalConfig.getAppServerConfigInfo(getContext()).getOtherFunction().getPush_appointment_time();
//                    if (startTime - nowTime < pushAppointmentTime * 60 * 1000) {//小于十分钟
//                        View inflate = LayoutInflater.from(getActivity()).inflate(R.layout.toast_view, null);
//                        ((TextView) inflate.findViewById(R.id.tv_content)).setText("精彩内容即将开始\n距离直播开始" + pushAppointmentTime + "分钟内\n无法预约");
//                        toastCenter(requireActivity(), inflate);
//                    } else {
//                        if (isClick) return;
//                        appointment(item);
//                    }
//                }

                }
        });

        liveReplayBroadcast = new LiveReplayBroadcast();
        liveReplayBroadcast.updateListState = this;
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LiveReplayBroadcast.UpdateState);
        intentFilter.addAction(LiveReplayBroadcast.UpdateChoose);
        getActivity().registerReceiver(liveReplayBroadcast, intentFilter);

    }

    /**
     * 预约的时候要的参数
     *
     * @param articleId
     * @param channelName
     */
    public void setArticleIdAndName(String articleId, String channelName) {
        contentId = articleId;
        this.channelName = channelName;
    }

    public void setListData(final List<ProgramListItem> list) {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                    return ;
                }
                try {
                    if (list.size() == 0) {
                        noProgram.setVisibility(View.VISIBLE);
                    } else {
                        liveProgramAdaptor.setListContentData(list);
                        final int idx = getLiveItem();
                        ProgramListItem item = liveProgramAdaptor.getItem(idx);
                        if (idx > 0 && GuideItemState.LIVE == ProgramListItem.getItemState(item)) {
                            //刚进来的时候 先滚动到正在直播的那去
                            if (MMKV.defaultMMKV().decodeBool(XKey.AUTO_PLAY, false)) {
                                liveProgramAdaptor.selectedIndex = idx;
                            }else{
                                liveProgramAdaptor.livingIndex = idx;
                            }
                            handler.postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    if (idx > 0) {
                                        programList.setSelection(idx - 1);
                                    } else {
                                        programList.setSelection(0);
                                    }
                                    //								liveProgramAdaptor.notifyDataSetChanged();
                                    updateLiveLabelDelay(idx);
                                }
                            }, 150);
                        }
                        programList.setAdapter(liveProgramAdaptor);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    if (noProgram != null) {
                        noProgram.setVisibility(View.VISIBLE);
                    }
                } finally {
                    if (isLoadingProgramList != null)
                        isLoadingProgramList.setVisibility(View.GONE);
                }
            }
        }, 1000);
    }

    /**
     * 定时去刷新通知更新 取到当前正在播放的节目单  把结束时间 减去当前时间的时间差
     * 延时去刷 把之前正在播放的置为回看 然后再把下一个正在播放的标签置成正在播放
     *
     * @param idx
     */
    protected ProgramListItem updateLiveLabelDelay(int idx) {
        ProgramListItem item = liveProgramAdaptor.getItem(idx);
        if (GuideItemState.LIVE != ProgramListItem.getItemState(item))
            return item;
        Date now = new Date(System.currentTimeMillis());
        if (item!= null){
            Date endDate = DateParse.parseDate(item.getEndtime(), null);
            long delay = endDate.getTime() - now.getTime();
            delay += 2000;
            handler.sendEmptyMessageDelayed(1, delay);
        }
        return item;
    }

    @SuppressLint("HandlerLeak")
    class ProgramListHandle extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                return ;
            }
            //通知更新一下 主要是把正在播放的显示成回看 即将播放的显示成正在播放
            if (msg.what == 1) {
                liveProgramAdaptor.notifyDataSetChanged();
                int idx = getLiveItem();
                updateLiveLabelDelay(idx);
                sendUpdateStateBroad();
            }
        }
    }

    /**
     * 发广播通知更新所有节目单状态
     */
    protected void sendUpdateStateBroad() {
        Intent intent = new Intent();
        intent.setAction(LiveReplayBroadcast.UpdateState);
        intent.putExtra("index", liveTableIndex);
        if (getActivity()!= null)
         getActivity().sendBroadcast(intent);
    }

    protected void sendUpdateChoose() {
        Intent intent = new Intent();
        intent.setAction(LiveReplayBroadcast.UpdateChoose);
        intent.putExtra("index", liveTableIndex);
        if (getActivity()!= null)
        getActivity().sendBroadcast(intent);
    }

    protected int getLiveItem() {
        for (int idx = 0; idx < liveProgramAdaptor.getCount(); idx++) {
            ProgramListItem item = liveProgramAdaptor.getItem(idx);
            if (ProgramListItem.getItemState(item).equals(GuideItemState.LIVE)) {
                return idx;
            }
        }
        return 0;
    }

    @Override
    public void updateListPlayState(int tableIndex) {
        if (liveTableIndex != tableIndex) {
            liveProgramAdaptor.notifyDataSetChanged();
            int idx = getLiveItem();
            updateLiveLabelDelay(idx);
        }
    }

    @Override
    public void updateChoosePlayIndex(int tableIndex) {
        if (liveTableIndex != tableIndex) {
            liveProgramAdaptor.selectedIndex = -1;
        }
        liveProgramAdaptor.notifyDataSetChanged();
    }
    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putParcelable("data", catalogItem);
        super.onSaveInstanceState(outState);
    }

    private void appointment(ProgramListItem item) {
        progressBar.setVisibility(View.VISIBLE);
        isClick = true;
        HashMap<String, Object> map = new HashMap<>();
        map.put("user_id", UserInfo.userinfo.getUserid());
        map.put("title", channelName);
        map.put("type", 3);
        map.put("content_id", contentId);
        map.put("start_time", item.getStarttime());
        map.put("end_time", item.getEndtime());
        map.put("playbill_id", item.getId());
        map.put("name", item.getName());

        DataInvokeUtil.getZiMeiTiApi()
                .appointment(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull JSONObject jsonObject) {
                        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                            return ;
                        }
                        isClick = false;
                        progressBar.setVisibility(View.GONE);
                        if (jsonObject.optBoolean("state")) {
                            item.setAppointment(true);
                            toastCenter(requireActivity(), "预约成功", false);
                            liveProgramAdaptor.notifyDataSetChanged();
                            JSONObject data = jsonObject.optJSONObject("data");
                            if (data != null) {
                                int id = data.optInt("id");
                                item.setAppointmentId(id);
                            }

                        } else {
                            toastCenter(requireActivity(), "网络异常，请检查网络", false);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });


    }

    /**
     * 取消预约
     */
    private void cancelAppointment(ProgramListItem item) {
        progressBar.setVisibility(View.VISIBLE);
        isClick = true;
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", item.getAppointmentId());
        DataInvokeUtil.getZiMeiTiApi()
                .cancelAppointment(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {

                    }

                    @Override
                    public void onNext(@NonNull JSONObject jsonObject) {
                        if (getActivity() == null || requireActivity().isFinishing()||requireActivity().isDestroyed()) {
                            return ;
                        }
                        isClick = false;
                        progressBar.setVisibility(View.GONE);
                        if (jsonObject.optBoolean("state")) {
                            item.setAppointment(false);
                            toastCenter(requireActivity(), "取消预约成功", false);
                            liveProgramAdaptor.notifyDataSetChanged();
                        } else {
                            toastCenter(requireActivity(), "网络异常，请检查网络", false);
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

}